<template>
  <!-- 搜索框 -->
    <SearchBox :options="mList" @search="handleSearch"  :clear="clear"></SearchBox>
    <!-- 表格 -->
    <DataTable :tableData="tableData" @deleteD="handleDelete"></DataTable>
    <!-- 分页 -->
    <pagination :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"> </pagination>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import SearchBox from '../components/SearchBox';
import DataTable from '../components/DataTable';
import pagination  from '../components/pagination';
import axios from 'axios';

//搜索框里项目list
let mList = ref([])
let clear= ref(false)
let tableData= ref([])
let total= ref(0)

//分页的变量
let currentPage=ref(1)
let pageSize=ref(10)

const message = ref('Hello, Vue 3!');
onMounted(() => {
    fetchMn()
    fetchData()
});

//下拉菜单搜索数据
function handleSearch(data){
    console.log(data)
    axios.get('http://localhost:3000/xiangmu/?name=' + data , {
    params: {
      _page: currentPage.value,
      _per_page: pageSize.value
    }
  })
    .then(response => {
            // 请求成功时更新tableData
      tableData.value=response.data.data
      total.value= response.data.items
  
    })
    .catch(error => {
      console.error("Error fetching data:", error); // 请求失败时打印错误信息
    });
}

//获取首页数据
function fetchData(){
  axios.get('http://localhost:3000/xiangmu/' , {
    params: {
      _page: currentPage.value,
      _per_page: pageSize.value
    }
  })
  .then(res => {
     tableData.value=res.data.data
     total.value= res.data.items

  })
  .catch(err => {
    console.error(err); 
  })
}

// 切换每页的条数时
function handleSizeChange(size){
  pageSize.value=size
  clear.value= true
  axios.get('http://localhost:3000/xiangmu/' , {
    params: {
      _page: currentPage.value,
      _per_page: pageSize.value
    }
  })
  .then(res => {
     tableData.value=res.data.data
  })
  .catch(err => {
    console.error(err); 
  })
}
// 切换页码时
function handleCurrentChange(page){
  clear.value= true
  currentPage.value= page
  axios.get('http://localhost:3000/xiangmu/' , {
    params: {
      _page: currentPage.value,
      _per_page: pageSize.value
    }
  })
  .then(res => {
     tableData.value=res.data.data
  })
  .catch(err => {
    console.error(err); 
  })
}


// 获取下拉菜单数据
function fetchMn(){
  axios.get("http://localhost:3000/Mn")
  .then(res => {
    mList.value=res.data
  })
  .catch(err => {
    console.error(err); 
  })
}



//删除数据
function handleDelete(data) { 
  axios.delete('http://localhost:3000/xiangmu/' + data)
    .then(res => {
      fetchData();
    })
    .catch(err => {
      console.error(err);
    })

 }

</script>